<?php
/**
 * @author 595949289@qq.com
 * @datetime 2022/9/19 22:24
 */

namespace CuiFox\AliOss;

class Uploader
{
    private $tmpPath;  //PHP文件临时目录
    private $blobNum; //第几个文件块
    private $totalBlobNum; //文件块总数
    private $fileName; //文件名
    private $filePath;

    public function __construct($tmpPath, $blobNum, $totalBlobNum, $fileName, $filePath)
    {
        $this->tmpPath = $tmpPath;
        $this->blobNum = $blobNum;
        $this->totalBlobNum = $totalBlobNum;
        $this->fileName = $fileName;
        $this->filePath = $filePath . '/';
    }

    //判断是否是最后一块，如果是则进行文件合成并且删除文件块
    private function fileMerge()
    {
        if ($this->blobNum == $this->totalBlobNum) {
            $blob = '';
            for ($i = 1; $i <= $this->totalBlobNum; $i++) {
                $blob .= file_get_contents($this->filePath . '/' . $this->fileName . '__' . $i);
            }
            file_put_contents($this->filePath . '/' . $this->fileName, $blob);
            $this->deleteFileBlob();
        }
    }

    //删除文件块
    private function deleteFileBlob()
    {
        for ($i = 1; $i <= $this->totalBlobNum; $i++) {
            @unlink($this->filePath . '/' . $this->fileName . '__' . $i);
        }
    }

    //移动文件
    private function moveFile()
    {
        $this->touchDir();
        $filename = $this->filePath . '/' . $this->fileName . '__' . $this->blobNum;
        move_uploaded_file($this->tmpPath, $filename);
    }

    /**
     * @return string
     * @throws \Exception
     */
    public function handle()
    {
        if (!file_exists($this->filePath)) {
            @mkdir($this->filePath, 0775, true);
        }
        $this->moveFile();
        $this->fileMerge();

        $exists = file_exists($this->filePath . '/' . $this->fileName . '__' . $this->blobNum);
        if ($this->blobNum != $this->totalBlobNum && $exists) {
            throw new \Exception('Waiting for all');
        }

        if (!file_exists($this->filePath . '/' . $this->fileName)) {
            throw new \Exception('File not exists');
        }

        return $this->filePath . '/' . $this->fileName;
    }

    //建立上传文件夹
    private function touchDir()
    {
        if (!file_exists($this->filePath)) {
            @mkdir($this->filePath, 0775, true);
        }
    }
}